package servlet;

import java.io.IOException;
import java.util.Random;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import service.customer.CustomerService;
import service.customer.CustomerServiceFactory;

import entities.Customer;

public class SignUpServlet extends HttpServlet
{

	private static final long serialVersionUID = 1L;

	/**
	 * 
	 */
	public SignUpServlet() 
	{
	}
	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		
		Customer customer = createCustomer(request);;
		String addr = null;
		
		// Get the factory to create services. This is obtained from the web.xml configuration file
		// from parameter ServiceFactoryType
		CustomerServiceFactory factory = CustomerServiceFactory.getFactory(ServletInitParams.getServiceFactoryType(this));
		// Get an instance of the student service, as given by the factory
		CustomerService service = factory.getInstance();

		try {
			service.addCustomer(customer);
			session.setAttribute("customer", customer);
			addr = "./html/customerAdded.jsp";
		} catch (dao.RecordDuplicateException e) {
			session.setAttribute("customer", customer);
			addr = "./html/customerDuplicate.jsp";
		}
		// forward the request to the page previously determined
		RequestDispatcher dispatcher = request.getRequestDispatcher(addr);
		dispatcher.forward(request, response);

	}
	
	private Customer createCustomer(HttpServletRequest request) {
		
		Random generator2 = new Random( 19580427 );
		
		String name = request.getParameter("name");
		String lastname = request.getParameter("last_name");
		String street = request.getParameter("street");
		String aptno  = request.getParameter("apt_num");
		String city = request.getParameter("city");
		String state = request.getParameter("state");
		String zipcode = request.getParameter("zipcode");
		String country = request.getParameter("country");
		
		String username = request.getParameter("username");
		String pass = request.getParameter("password");
		Long userid = generator2.nextLong();
		String email = "lkljlad";
		
		Customer customer = null;
		customer = Customer.newInstance(username, name, lastname, email, userid, pass, street, aptno, zipcode, state, city, country);
		
		return customer;
	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		doGet(request, response);
	}
}
